package com.js.basehttp;

// Created by JS on 2020/6/15.

import com.jakewharton.retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import com.js.basehttp.interceptor.TokenHeaderInterceptor;

import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class RxJavaRetrofit {

    private volatile static Retrofit retrofit;
    private static OkHttpClient client;

    private RxJavaRetrofit() {
    }

    public static Retrofit getRetrofit(String address) {
        return getRetrofit(address, null);
    }

    public static Retrofit getRetrofit(String address, String token) {
        if (client == null) {
            createNewClient(token);
        }
        return new Retrofit.Builder()
                .client(client)
                .baseUrl(address)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .build();
    }

    public static void createNewClient(String token) {
        client = new OkHttpClient()
                .newBuilder()
                .connectTimeout(600, TimeUnit.SECONDS)
                .readTimeout(600, TimeUnit.SECONDS)
                .addNetworkInterceptor(new TokenHeaderInterceptor(token))
                .build();
    }
}
